package com.jinlejia.erp.ui.new_house.recommend;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.bean.Customer;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.ui.customer.RecordCustomer1Activity;
import com.jinlejia.erp.ui.new_house.adapter.CustomerAdapter;
import com.jinlejia.erp.utils.CharacterParser;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.PinyinCustomerComparator;
import com.jinlejia.erp.widget.SideBar;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

public class CustomerListActivity extends AppCompatActivity implements View.OnClickListener{

    private ListView listView;
    private SideBar sideBar;
    private CustomerAdapter adapter;
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    private List<Customer> SourceDateList = new ArrayList<>();

    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinCustomerComparator pinyinComparator;
    private String type;
    private ProgressDialog progressDialog;
    private ArrayList<String> firstCase = new ArrayList<>();

    private int page = 1;
    private String nameword = "";
    //这个tag主要用来判断是不是第一次请求接口，如果是则不能下拉加载
    private int tag = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_list);
        if (getIntent().hasExtra("type")) {
            type = getIntent().getStringExtra("type");
        }
        progressDialog = new ProgressDialog(this, "请稍后...");
        initView();
        initData(null, page, 100);
    }

    private void initView() {
        ImageView back = findViewById(R.id.id_back);
        ImageView addClient = findViewById(R.id.id_add_client);
        listView = findViewById(R.id.id_list_view);
        RelativeLayout empty = findViewById(R.id.id_empty);
        listView.setEmptyView(empty);
        EditText search = findViewById(R.id.id_search_clients);
        sideBar = findViewById(R.id.id_side_bar);
        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinCustomerComparator();
        back.setOnClickListener(this);
        addClient.setOnClickListener(this);
        //设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                if (adapter != null) {
                    int position = adapter.getPositionForSection(s.charAt(0));
                    if (position != -1) {
                        listView.setSelection(position);
                    }
                }
            }
        });
        //根据输入框输入值的改变来过滤搜索
        search.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                if (TextUtils.isEmpty(s.toString())){
                    tag = 0;
                    page = 1;
                    nameword = s.toString();
                    initData(nameword,page,100);
                }else{
                    nameword = s.toString();
                    page = 1;
                    initData(nameword,page,20);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                //这里要利用adapter.getItem(position)来获取当前position所对应的对象
                if (!TextUtils.isEmpty(type)) {
                    //选择客户
                    Intent intent = new Intent();
                    intent.putExtra("name", ((Customer) adapter.getItem(position)).getName());
                    intent.putExtra("tel", ((Customer) adapter.getItem(position)).getTel());
                    intent.putExtra("code", ((Customer) adapter.getItem(position)).getCsCode());
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });


        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            //当滑动状态发生改变的时候执行
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    //当不滚动的时候
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        //判断是否是最底部
                        if (view.getLastVisiblePosition() == (view.getCount()) - 1) {
                            if (tag!=1){
                                page = page + 1;
                                initData(nameword, page, 20);
                            }
                        }
                        break;
                }
            }

            //正在滑动的时候执行
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }
        });

    }

    private void initData(String keyWord, final int pageIndex, int pageSize) {
        progressDialog.show();
        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        if (!TextUtils.isEmpty(keyWord)) {
            jsonObject.put("name", keyWord);
        }else{
            jsonObject.remove("name");
        }
        jsonObject.put("pageIndex", pageIndex);
        jsonObject.put("pageSize", pageSize);
        tag = tag + 1;
        OkHttpUtils.postString()
                .url(ApiConfig.RECOMMEND_CUSTOMER_LIST)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        call.cancel();
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing())
                            progressDialog.dismiss();
                        if (DataFilter.filter(CustomerListActivity.this, response)) {
                            JSONArray data = JSON.parseArray(response.get("data").toString());
                            ArrayList<Customer> dateList = JSON.parseObject(data.toJSONString(), new TypeReference<ArrayList<Customer>>() {
                            });
                            SourceDateList = filledData(dateList);
                            if (pageIndex == 1) {
                                // 根据a-z进行排序源数据
                                Collections.sort(SourceDateList, pinyinComparator);
                                adapter = new CustomerAdapter(CustomerListActivity.this, SourceDateList);
                                listView.setAdapter(adapter);
                                sideBar.setList(firstCase);

                            } else {
                                Collections.sort(SourceDateList, pinyinComparator);
                                adapter.updateListView(SourceDateList);
                            }
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.id_back:
                finish();
                break;
            case R.id.id_add_client:
                //添加客户
                startActivityForResult(new Intent(this, RecordCustomer1Activity.class), 101);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 101) {
                Intent intent = new Intent();
                intent.putExtra("name", data.getStringExtra("name"));
                intent.putExtra("tel", data.getStringExtra("tel"));
                intent.putExtra("code", data.getStringExtra("code"));
                setResult(RESULT_OK, intent);
                finish();
            }
        }
    }

    /**
     * 为ListView填充数据
     *
     * @param
     * @return
     */
    private List<Customer> filledData(ArrayList<Customer> data) {
        List<Customer> mSortList = new ArrayList<>();

        for (int i = 0; i < data.size(); i++) {
            Customer clients = new Customer();
            clients.setName(data.get(i).getName());
            clients.setTel(data.get(i).getTel());
            clients.setCsCode(data.get(i).getCsCode());
            //汉字转换成拼音
            String pinyin = characterParser.getSelling(data.get(i).getName());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                clients.setSortLetters(sortString.toUpperCase());
                if (!firstCase.contains(sortString)) {
                    firstCase.add(sortString);
                }
            } else {
                clients.setSortLetters("#");
//                firstCase.add("#");
            }

            mSortList.add(clients);
        }
        return mSortList;

    }



    @Override
    protected void onDestroy() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        super.onDestroy();
    }


}
